package com.example.sys.login

import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_common.mvi.BaseActivity
import com.example.sys.databinding.ActivityLoginBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindUiState()
        v.loginBtn.setOnClickListener {
            var loginPwdEdt = v.loginPwdEdt.text.toString()
            var loginUserEdt: String = v.loginUserEdt.text.toString()
            if (TextUtils.isEmpty(loginPwdEdt)||TextUtils.isEmpty(loginUserEdt)){
                ToastUtils.showShort("不能为空")
                return@setOnClickListener
            }
                val map : HashMap<String ,Any> = java.util.HashMap()
                map["time"] = ""+System.currentTimeMillis()
                map["uName"] = loginUserEdt
                map["uPwd"] = loginPwdEdt
                vm.login(map)
        }
    }
    private fun bindUiState(){
        lifecycleScope.launch(Dispatchers.Main){
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.uiStateFlow.collect{
                    if (it.entity.statuesCode==200){
                        if (it.entity.msg == "登录成功"){
                            SPUtils.getInstance().put("token",it.entity.values.token)
                            ToastUtils.showShort("登录成功")
                            SPUtils.getInstance().put("dept_id",it.entity.values.dept_id)
                            SPUtils.getInstance().put("uName",it.entity.values.uName)
                            SPUtils.getInstance().put("uId",it.entity.values.uId)
                            ARouter.getInstance().build("/home/HomeActivity").withString("url", it.entity.values.homeURL).navigation()
                        }else{
                            ToastUtils.showShort("登录失败")
                        }
                    }
                }
            }
        }
    }
    override fun createVM(): LoginViewModel {
        return viewModels<LoginViewModel>().value
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityLoginBinding.inflate(inflater)
    }
}